# 角色管理接口 - 增强版，支持权限绑定管理
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt, get_jwt_identity
from backend.models.role import Role
from backend.models.permission import Permission
from backend.models.role_permission import RolePermission
from backend.infrastructure.database import db
from backend.services.role_admin_service import (
    get_role_list, create_role, update_role, delete_role
)
from backend.api.user_api import admin_required
from backend.services.unified_log_service import log_service
from backend.models.system_log import SystemLog

@jwt_required()
@admin_required
def list_roles():
    roles = get_role_list()
    return jsonify({'success': True, 'data': roles})

@jwt_required()
@admin_required
def add_role():
    data = request.get_json(force=True, silent=True)
    result = create_role(data)
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        # ✅ 修复：直接使用Role对象，不需要再次查询
        role = result.get('data')
        if role:
            log = SystemLog.log_create(
                record=role,  # ✅ 直接使用Role对象
                operator=operator,
                ip_address=ip_address
            )
            if log:
                db.session.add(log)
                db.session.commit()
    
    # ✅ 修复：返回字典格式给前端
    if result.get('success'):
        result['data'] = result['data'].to_dict()
    
    return jsonify(result)

@jwt_required()
@admin_required
def edit_role(role_id):
    data = request.get_json(force=True, silent=True)
    
    # 获取修改前的角色数据
    old_role = Role.query.get(role_id)
    old_data = old_role.to_dict() if old_role else None
    
    result = update_role(role_id, data)
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        # ✅ 修复：直接使用Role对象，不需要再次查询
        role = result.get('data')
        if role:
            log = SystemLog.log_update(
                record=role,  # ✅ 直接使用Role对象
                old_data=old_data,
                operator=operator,
                ip_address=ip_address
            )
            if log:
                db.session.add(log)
                db.session.commit()
    
    # ✅ 修复：返回字典格式给前端
    if result.get('success'):
        result['data'] = result['data'].to_dict()
    
    return jsonify(result)

@jwt_required()
@admin_required
def remove_role(role_id):
    # 获取删除前的角色数据
    old_role = Role.query.get(role_id)
    old_data = old_role.to_dict() if old_role else None
    
    result = delete_role(role_id)
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        # ✅ 修复：使用old_role对象而不是字典
        if old_role:
            log = SystemLog.log_delete(
                record=old_role,  # ✅ 传递Role对象
                operator=operator,
                ip_address=ip_address
            )
            if log:
                db.session.add(log)
                db.session.commit()
    
    return jsonify(result)

# ========== 新增：角色权限绑定管理API ==========

@jwt_required()
@admin_required
def get_role_permissions(role_id):
    """获取角色的权限列表"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({
                'success': False,
                'message': '角色不存在'
            }), 404
        
        # 获取角色已有的权限
        role_permissions = RolePermission.query.filter_by(role_id=role_id).all()
        assigned_permission_ids = [rp.permission_id for rp in role_permissions]
        
        # 获取所有权限（包括active和enabled状态）
        all_permissions = Permission.query.filter(Permission.status.in_(['active', 'enabled'])).all()
        
        # 按类别分组权限
        permission_groups = {}
        for perm in all_permissions:
            category = perm.code.split(':')[0]
            if category not in permission_groups:
                permission_groups[category] = {
                    'category': category,
                    'permissions': []
                }
            
            permission_groups[category]['permissions'].append({
                'id': perm.id,
                'code': perm.code,
                'name': perm.name,
                'description': perm.description,
                'assigned': perm.id in assigned_permission_ids
            })
        
        return jsonify({
            'success': True,
            'data': {
                'role': role.to_dict(),
                'permission_groups': list(permission_groups.values()),
                'total_permissions': len(all_permissions),
                'assigned_permissions': len(assigned_permission_ids)
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取角色权限失败: {str(e)}'
        }), 500

@jwt_required()
@admin_required
def update_role_permissions(role_id):
    """更新角色权限绑定"""
    try:
        data = request.get_json(force=True, silent=True)
        if not data:
            return jsonify({
                'success': False,
                'message': '请求数据不能为空'
            }), 400
        
        role = Role.query.get(role_id)
        if not role:
            return jsonify({
                'success': False,
                'message': '角色不存在'
            }), 404
        
        permission_ids = data.get('permission_ids', [])
        if not isinstance(permission_ids, list):
            return jsonify({
                'success': False,
                'message': '权限ID列表格式错误'
            }), 400
        
        # 验证权限ID的有效性
        valid_permissions = Permission.query.filter(
            Permission.id.in_(permission_ids),
            Permission.status == 'active'
        ).all()
        
        if len(valid_permissions) != len(permission_ids):
            return jsonify({
                'success': False,
                'message': '包含无效的权限ID'
            }), 400
        
        # 删除旧的权限关联
        RolePermission.query.filter_by(role_id=role_id).delete()
        
        # 创建新的权限关联
        for permission_id in permission_ids:
            role_permission = RolePermission(
                role_id=role_id,
                permission_id=permission_id
            )
            db.session.add(role_permission)
        
        db.session.commit()
        
        # 记录操作日志
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 获取更新后的权限信息作为新数据
        updated_role_data = role.to_dict()
        updated_role_data['permissions'] = [{'id': pid, 'assigned': True} for pid in permission_ids]
        
        # 记录系统管理操作日志 - 权限更新
        log = SystemLog.log_update(
            record=role,
            old_data={'permissions': '权限更新前状态'},  # 可以改进为记录具体的旧权限
            operator=operator,
            ip_address=ip_address
        )
        if log:
            # 自定义详细信息以包含权限更新内容
            log.detail = f"更新角色权限: {role.name} - 分配了{len(permission_ids)}个权限"
            db.session.add(log)
            db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'角色权限更新成功，共分配{len(permission_ids)}个权限',
            'data': {
                'role_id': role_id,
                'permission_count': len(permission_ids)
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新角色权限失败: {str(e)}'
        }), 500

@jwt_required()
@admin_required  
def get_all_permissions():
    """获取所有权限列表（用于权限选择）"""
    try:
        permissions = Permission.query.filter(Permission.status.in_(['active', 'enabled'])).order_by(Permission.code).all()
        
        # 按类别分组
        permission_groups = {}
        for perm in permissions:
            category = perm.code.split(':')[0]
            if category not in permission_groups:
                permission_groups[category] = {
                    'category': category,
                    'category_name': get_category_name(category),
                    'permissions': []
                }
            
            permission_groups[category]['permissions'].append({
                'id': perm.id,
                'code': perm.code,
                'name': perm.name,
                'description': perm.description
            })
        
        return jsonify({
            'success': True,
            'data': {
                'permission_groups': list(permission_groups.values()),
                'total_permissions': len(permissions)
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取权限列表失败: {str(e)}'
        }), 500

def get_category_name(category):
    """获取权限类别的中文名称"""
    category_names = {
        'user': '用户管理',
        'student': '学生档案',
        'vision': '视力数据',
        'intervention': '干预记录',
        'followup': '随访管理',
        'report': '报告管理',
        'miniprogram': '小程序功能',
        'social': '社交功能',
        'feedback': '反馈管理',
        'system': '系统管理',
        'role': '角色管理',
        'permission': '权限管理',
        'log': '日志管理',
        'data': '数据权限',
        'audit': '审核权限'
    }
    return category_names.get(category, category)

@jwt_required()
@admin_required
def get_all_roles():
    """获取所有角色列表（用于前端界面）"""
    try:
        roles = Role.query.filter_by(status='active').order_by(Role.id).all()
        
        role_list = []
        for role in roles:
            # 获取角色权限数量
            permission_count = len([rp for rp in role.permissions])
            
            role_list.append({
                'id': role.id,
                'name': role.name,
                'description': role.description,
                'status': role.status,
                'permission_count': permission_count
            })
        
        return jsonify({
            'success': True,
            'data': role_list,
            'total': len(role_list)
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取角色列表失败: {str(e)}'
        }), 500

@jwt_required()
@admin_required
def get_all_permissions_simple():
    """获取所有权限列表（简化版，按类别分组）"""
    try:
        permissions = Permission.query.filter(Permission.status.in_(['active', 'enabled'])).order_by(Permission.code).all()
        
        # 按类别分组
        categories = {}
        for perm in permissions:
            category = perm.code.split(':')[0]
            if category not in categories:
                categories[category] = []
            
            categories[category].append({
                'id': perm.id,
                'code': perm.code,
                'name': perm.name,
                'description': perm.description
            })
        
        return jsonify({
            'success': True,
            'data': {
                'categories': categories,
                'total_permissions': len(permissions)
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取权限列表失败: {str(e)}'
        }), 500
